package com.power.config;

import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import org.springdoc.core.GroupedOpenApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

@Configuration
public class OpenApiConfig {

    @Autowired
    private SwaggerProperties swaggerProperties;

    @Autowired
    private Environment environment;
    private  boolean flag = true;

    @Bean
    public GroupedOpenApi customOpenApi() {

        String[] activeProfiles = environment.getActiveProfiles();
        for (String ap : activeProfiles) {
            if ("pro".equals(ap)) {
                flag = false;
                break;
            }
        }

        return GroupedOpenApi.builder()
                .group("public")
                .pathsToMatch("/**")
                .addOpenApiCustomiser(openApi -> customizeOpenApi(openApi, flag))
                .build();
    }

    private void customizeOpenApi(OpenAPI openApi, boolean flag) {
        if (!flag) {
            openApi.info(new Info().title("API not available in production"));
        } else {
            openApi.info(new Info()
                    .title(swaggerProperties.getTitle())
                    .description(swaggerProperties.getDescription())
                    .version(swaggerProperties.getVersion())
                    .contact(new Contact()
                            .name(swaggerProperties.getName())
                            .url(swaggerProperties.getUrl())
                            .email(swaggerProperties.getEmail()))
                    .license(new License()
                            .name(swaggerProperties.getLicense())
                            .url(swaggerProperties.getLicenseUrl())));
        }
    }

    @Bean
    public OpenAPI springShopOpenAPI() {
        return new OpenAPI()
                .info(new Info()
                        .title(swaggerProperties.getTitle())
                        .description(swaggerProperties.getDescription())
                        .version(swaggerProperties.getVersion())
                        .contact(new Contact()
                                .name(swaggerProperties.getName())
                                .url(swaggerProperties.getUrl())
                                .email(swaggerProperties.getEmail()))
                        .license(new License()
                                .name(swaggerProperties.getLicense())
                                .url(swaggerProperties.getLicenseUrl())));
    }
}
